
// This is for mouse and button events
//
		// Startup
		//

var _isDown, _points, _r, _g, _rc, canvas, originalImageData;
		function onLoadEvent()
		{
			document.onselectstart = function() { return false; }
			document.onmousedown = function() { return false; }
			_points = new Array();
			_r = new DollarRecognizer();

			canvas = document.getElementById('myCanvas');
			_g = canvas.getContext('2d');
			_g.fillStyle = "rgb(0,255,0)";
			_g.strokeStyle = "rgb(0,255,0)";
			_g.lineWidth = 3;
			_g.font = "16px Gentilis";
			_rc = getCanvasRect(); // canvas rect on page
			_g.fillStyle = "rgb(255,255,136)";
			_g.fillRect(0, 0, _rc.width, 20);
			_isDown = false;
			
			
			
			
			//add touch and mouse event listeners
	canvas.addEventListener('touchstart', onTouchStart, false);
	canvas.addEventListener('mousedown', onMouseDown, false);
	
	//event listener for application cache updates
	//window.applicationCache.addEventListener('onupdateready', updateCache, false);
			
			
			
			
		}
		function getCanvasRect()
		{
			var w = canvas.width;
			var h = canvas.height;

			var cx = canvas.offsetLeft;
			var cy = canvas.offsetTop;
			while (canvas.offsetParent != null)
			{
				canvas = canvas.offsetParent;
				cx += canvas.offsetLeft;
				cy += canvas.offsetTop;
			}
			canvas = document.getElementById('myCanvas');
			return {x: cx, y: cy, width: w, height: h};
		}
		function getScrollY()
		{
			var scrollY = 0;
			if (typeof(document.body.parentElement) != 'undefined')
			{
				scrollY = document.body.parentElement.scrollTop; // IE
			}
			else if (typeof(window.pageYOffset) != 'undefined')
			{
				scrollY = window.pageYOffset; // FF
			}
			return scrollY;
		}
		//
		// Mouse Events
		//
		
		
		
		
		


function onTouchStart(e) {
	
	e.preventDefault();
		
	if (e.touches.length == 1) {
		
		startDraw(e.touches[0].pageX, e.touches[0].pageY);
            	
		canvas.addEventListener('touchmove', onTouchMove, false);
		canvas.addEventListener('touchend', onTouchEnd, false);
		canvas.addEventListener('touchcancel', onTouchCancel, false);
	}			
}
	
function onTouchMove(e) {
	
	e.preventDefault();		
	moveDraw(e.touches[0].pageX, e.touches[0].pageY, e.timeStamp);
}
	
function onTouchEnd(e) {
	
	e.preventDefault();
		
	if (e.touches.length == 0) {
		
		endDraw(e.changedTouches[0].pageX, e.changedTouches[0].pageY);					
		canvas.removeEventListener('touchmove', onTouchMove, false);
		canvas.removeEventListener('touchend', onTouchEnd, false);
		canvas.removeEventListener('touchcancel', onTouchCancel, false);
	}		
}
	
function onTouchCancel(e) {
					
	canvas.removeEventListener('touchmove', onTouchMove, false);
	canvas.removeEventListener('touchend', onTouchEnd, false);
	canvas.removeEventListener('touchcancel', onTouchCancel, false);
		
}
	
function onMouseDown(e) {
		
	startDraw(e.clientX, e.clientY);				
	canvas.addEventListener('mousemove', onMouseMove, false);
	canvas.addEventListener('mouseup', onMouseUp, false);
				
}
	
function onMouseMove(e) {
	
	moveDraw(e.clientX, e.clientY, e.timeStamp);
}
	
function onMouseUp(e) {
		
	endDraw(e.clientX, e.clientY);
	canvas.removeEventListener('mousemove', onMouseMove, false);
	canvas.removeEventListener('mouseup', onMouseUp, false);		
}

function startDraw(x,y) {
/*
	//if the colour picker is not visible, we must be in drawing mode
	if(!pickerEnabled) {
        
		//set defaults
		started = false;
		
		//get start position
		startX = x;
		startY = y - toolbarHeight;
            	
		ctx.lineCap = 'round';
		ctx.lineJoin = 'round';
		ctx.lineWidth = penSize; 
		ctx.globalCompositeOperation = 'source-over';	
		
		//save canvas image data for future undo event
		originalImageData = ctx.getImageData(0, 0, window.innerWidth, (window.innerHeight - toolbarHeight));
				
	}
	else {
		selectColor(x,y);
	}
	
	*/
	
	
	/*
	function mouseDownEvent(x, y)
		{
		*/
		//save canvas image data for future undo event
		originalImageData = _g.getImageData(0, 0, 600, 400);
		
		
			x -= _rc.x;
			y -= _rc.y - getScrollY();
			
			_points.length = 1;
			_points[0] = new Point(x, y);
			drawText("Recording unistroke...");
			_g.fillRect(x - 4, y - 3, 9, 9);
			_isDown = true;
			
			
		
			
			
			
			/*
		}
		*/
	
	
	
}

function moveDraw(x,y,t) {
	
	/*

	//if the colour picker is not visible, we must be in drawing mode
	if(!pickerEnabled) {
		
		ctx.beginPath();
		ctx.moveTo(startX, startY);

		if (!started) {

			timerStart = t;
			started = true;
		}
		else {
           
        	//calc velocity     
        	var time = t - timerStart;     
        	var distance = Math.sqrt(Math.pow(((y - toolbarHeight) - startY), 2) + Math.pow((x - startX), 2));        
        	var velocity = distance / time;
        	roundedVel = Math.round(velocity * 100) / 100;        
        	started = false;
		} 
	
		var lw = penSize * roundedVel;
	
		//set line width limits
		if (lw > 1) {
			ctx.lineWidth = 1;  
		}
		else if (lw < 0.1) {
			ctx.lineWidth = 0.1;
		} 
		else {
			ctx.lineWidth =  lw; 
		}             
        
        //set alpha opacity limits
		if (roundedVel > 1) {	
			ctx.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',1.0)';
		} 
		else if (roundedVel < 0.3) {
			ctx.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',0.3)';
		}
		else {
			ctx.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + roundedVel + ')';
		}
	
		ctx.lineTo(x, y - toolbarHeight);
		ctx.stroke();
		ctx.closePath();

		startX = x;
		startY = y - toolbarHeight;
	}
	else {	
		selectColor(x,y);	
	}
	
	*/
	
	
	/*
	function mouseMoveEvent(x, y)
		{
		*/
			if (_isDown)
			{
				x -= _rc.x;
				y -= _rc.y - getScrollY();
				_points[_points.length] = new Point(x, y); // append
				drawConnectedPoint(_points.length - 2, _points.length - 1);
			}
			/*
		}
		*/
}

function endDraw(x,y) {

/*
	if(pickerEnabled) {
		//return to our canvas drawing and hide the colour picker
		ctx.putImageData(originalImageData, 0, 0);			
		strokePickerEnabled = false;
        fillPickerEnabled = false;
		pickerEnabled = false;
	}
	
			*/
			
			/*
			function mouseUpEvent(x, y)
		{
		*/
			if (_isDown)
			{
				_isDown = false;
				if (_points.length > 0 && round((_r.Recognize(_points)).Score,2)>0.89)
			{
				undo();
			}
				if (_points.length >= 10)
				{
					var result = _r.Recognize(_points);
					drawText("Result: " + result.Name + " (" + round(result.Score,2) + ").");
				}
				else // fewer than 10 points were inputted
				{
					drawText("Too few points made. Please try again.");
				}
				
			}
			/*
		}
		*/
}
		
		
		
		
		
		
		
		
		
		
		
		
		
		function undo(){
			if (_points.length > 0 && round((_r.Recognize(_points)).Score,2)>0.89)
			{
				_g.putImageData(originalImageData, 0, 0);
			}	
		}
		
		
		
		function drawText(str)
		{
			
//			_g.fillStyle = "rgb(255,255,136)";
//			_g.fillRect(0, 0, _rc.width, 20);
//			_g.fillStyle = "rgb(0,0,255)";
//			_g.fillText(str, 1, 14);

document.getElementById('resultado').value=str;
		}
		function drawConnectedPoint(from, to)
		{
			_g.beginPath();
			_g.moveTo(_points[from].X, _points[from].Y);
			_g.lineTo(_points[to].X, _points[to].Y);
			_g.closePath();
			_g.stroke();
		}
		function round(n, d) // round 'n' to 'd' decimals
		{
			d = Math.pow(10, d);
			return Math.round(n * d) / d
		}
		//
		// Template Adding and Clearing
		//
		function onClickAddExisting()
		{
			if (_points.length >= 10)
			{
				var templates = document.getElementById('templates');
				var name = templates[templates.selectedIndex].value;
				//drawText("Adding \"" + name + "\" gesture and re-recognizing...");
				var num = _r.AddTemplate(name, _points);
				//alert("Gesture added as new \"" + name + "\" unistroke. There are now " + num + " \"" + name + "\" unistroke gestures defined.");
				//var result = _r.Recognize(_points);
				//drawText("Result: " + result.Name + " (" + round(result.Score,2) + ").");
				drawText("\"" + name + "\" added. Number of \"" + name + "\"s defined: " + num + ".");
			}
		}
		function onClickAddCustom()
		{
			alert("prueba");
			var name = document.getElementById('custom').value;
			if (_points.length >= 10 && name.length > 0)
			{
				//drawText("Adding \"" + name + "\" gesture and re-recognizing...");
				var num = _r.AddTemplate(name, _points);
				//alert("Gesture added as new \"" + name + "\" unistroke. There are now " + num + " \"" + name + "\" unistroke gestures defined.");
				//var result = _r.Recognize(_points);
				//drawText("Result: " + result.Name + " (" + round(result.Score,2) + ").");
				drawText("\"" + name + "\" added. Number of \"" + name + "\"s defined: " + num + ".");
			}
		}
		function onClickCustom()
		{
			document.onselectstart = function() { return true; }
			document.onmousedown = function() { return true; }
			document.getElementById('custom').select();
			document.onselectstart = function() { return false; }
			document.onmousedown = function() { return false; }
		}
		function onClickDelete()
		{
			var num = _r.DeleteUserTemplates(); // deletes any user-defined templates
			alert("All user-defined templates have been deleted. Only the 1 predefined unistroke gesture remains for each of the " + num + " gesture types.");
		}